//
//  YSGNurseAppointmentInfoDetailsViewModel.swift
//  EyeVisionForPatients
//
//  Created by liuyutian on 2022/4/1.
//  Copyright © 2022 QDSG. All rights reserved.
//

import UIKit
import HandyJSON

class YSGNurseAppointmentInfoDetailsViewModel: NSObject {
    

    var model : YSGNurseAppointmentInfoDetailsModel?
    var consumeMaterials: [YSGNurseAppointmentInfoConsumablessModel] = []
    var consumeMaterialsDic : Dictionary<String, Any>?
    var consumeMaterialsArray : Array<String> = []
    
    //总金额
    var sumMoney : NSDecimalNumber?
    var unPayMoney : NSDecimalNumber?
    

    
    ///行高
    func rowHeight(_ row : Int) -> Float {
        let consumablessModels : Array<YSGNurseAppointmentInfoConsumablessModel> =  consumeMaterialsDic?[consumeMaterialsArray[row]] as! Array<YSGNurseAppointmentInfoConsumablessModel>
        
        switch consumablessModels.first?.orderStatus {
        case .unpaid:
            return 116.0 + Float(consumablessModels.count * 30)
        default:
            return 78.0 + Float(consumablessModels.count * 30)
        }
    }
    
    //计算
    func getSumMoneyAttributedString() -> NSAttributedString
    {
        
        let sumMoneyString : String =  String(format: "%.2f", (sumMoney?.floatValue ?? 0) / 100.0)
        let unPayMoneyString : String = String(format: "%.2f", (unPayMoney?.floatValue ?? 0) / 100.0)
        
        let priceString = NSMutableAttributedString(
            string: "合计" + sumMoneyString  + "元  " + (unPayMoney?.floatValue == 0 ? "" : "含" +  unPayMoneyString + "元待支付" ),
            attributes: [NSAttributedString.Key.font:
                UIFont(name: "PingFang SC", size: 12.0)!])
        
        
        priceString.addAttribute(NSAttributedString.Key.foregroundColor,value:UIColor.warning, range: NSRange(location:2,length:sumMoneyString.count + 2))
        priceString.addAttribute(NSAttributedString.Key.font,value:UIFont(name: "PingFangSC-Semibold", size: 14.0)!, range: NSRange(location:0,length:sumMoneyString.count + 5))
        if (unPayMoney?.floatValue != 0){
            priceString.addAttribute(NSAttributedString.Key.foregroundColor,value:UIColor.init(hex: "#F2A37D"), range: NSRange(location:sumMoneyString.count + 5,length:unPayMoneyString.count + 5))
        }
        return priceString
    }
    
    
    ///辅材订单整合
    func getConsumabless(){
        
        var dic = Dictionary<String, Any>()
        var consumablessArray : Array<Any>?
        for item in consumeMaterials {
            if dic[item.orderId!] == nil{
                consumablessArray = Array<Any>()
                consumeMaterialsArray.append(item.orderId ?? "")
            }
            consumablessArray?.append(item)
            dic[item.orderId!] = consumablessArray
            
            if item.orderStatus == .unpaid
            {
                unPayMoney = unPayMoney?.adding(NSDecimalNumber(string: item.orderAmount ?? "0"))
            }
            sumMoney = sumMoney?.adding(NSDecimalNumber(string: item.orderAmount ?? "0"))
            
        }
        consumeMaterialsDic = dic
    }
    

    
    func getProjectDetails(appointmentId: String,finished: @escaping (_ model: YSGNurseAppointmentInfoDetailsModel?, _ errorMsg: String?, _ code: HttpCode) -> Void) {
        HttpTool.shared.request(target: ApiManager.appointment_get_listDetail(appointmentId: appointmentId), success: {[weak self] (json, code) in
            
            switch code {
            case .failure:
                finished(nil , json["message"].description, .failure)
            case .success:
                self?.sumMoney = NSDecimalNumber(string: "0")
                self?.unPayMoney = NSDecimalNumber(string: "0")
                
                
                if let models = JSONDeserializer<YSGNurseAppointmentInfoConsumablessModel>.deserializeModelArrayFrom(json: json["data"]["consumeMaterials"].description) as? [YSGNurseAppointmentInfoConsumablessModel] {
                    self?.consumeMaterials = models
                    self?.getConsumabless()
                }
                
                
                if let model = JSONDeserializer<YSGNurseAppointmentInfoDetailsModel>.deserializeFrom(json: json["data"].description){
                    ///加上订单金额
                    self?.sumMoney = self?.sumMoney?.adding(NSDecimalNumber(string: model.orderAmount ))
                    
                    finished(model, nil, .success)
                } else {
                    finished(nil, json["message"].description, .failure)
                }
            }
        }) { errorMsg in
            finished(nil , errorMsg, .failure)
        }
    }
}


struct YSGNurseAppointmentInfoConsumablessModel : HandyJSON{
    var orderAmount: String?

    var sendPayTime: String?

    var consumables: String?

    var type: Int = 0

    var price: String?

    var appointmentId: String?

    var consumeId: String?

    var number: String?

    var orderId: String?

    var orderStatus: orderStatusEnum?

    var orderNumber: String?

    var consumablesCode: String?

}


struct YSGNurseAppointmentInfoDetailsModel : HandyJSON{
    
    var chargeItemCode : String?
    
    var isTrichiasis: Int = 0

    var appointmentId: String?

    var commentScore: String?

    var isRemove: Int = 0

    var orderStatus: orderStatusEnum?

    var commentContent: String?

    var patientName: String?

    var orderNumber: String?

    var sendPayTime: String?

    var sex: String?

    var projectTitle: String?

    var isEyeRed: Int = 0

    var appointmentTime: String?

    var nurseCompleteTime: String?

    var fare : String = "0"
    
    var nursePhone: String?

    var orderAmount: String = "0"

    var isSecretion: Int = 0

    var isUnobstructed: Int = 0

    var birth: String?

    var nurseName: String?

    var isSuture: Int = 0

    var appointmentStatus: appointmentStatusEnum?

    var adress: String?

    var patientPhone: String?

    var age: String?

    var createTime: String?

    var nurseReceivingTime: String?

    var suturePosition: String?

    var payWay: Int = 0

    var nurseStatus: Int = 0

    var orderId: String?
    
    var consumeMaterials: [YSGNurseAppointmentInfoConsumablessModel]?
}
